/*
 * @lc app=leetcode.cn id=519 lang=typescript
 *
 * [519] 随机翻转矩阵
 */

// @lc code=start
class Solution {
  private total: number;
  private hash: Map<number, number> = new Map();
  constructor(private m: number, private n: number) {
    this.m = m;
    this.n = n;
    // 值为0的元素个数
    this.total = m * n;
    this.hash = new Map();
  }

  flip(): number[] {
    if (this.total === 0) {
      return [];
    }
    // 随机选择一个数
    let num = Math.floor(Math.random() * this.total);
    this.total--;
    // 如果这个数已经出现过了，就选择哈希表中的数
    const idx = this.hash.get(num) || num;
    // 将num映射为值为0的元素个数
    this.hash.set(num, this.hash.get(this.total) || this.total);
    // 一维坐标转换为二维坐标
    return [Math.floor(idx / this.n), idx % this.n];
  }

  reset(): void {
    this.total = this.m * this.n;
    this.hash.clear();
  }
}

/**
 * Your Solution object will be instantiated and called as such:
 * var obj = new Solution(m, n)
 * var param_1 = obj.flip()
 * obj.reset()
 */
// @lc code=end
